<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\roominfoService;
use think\Db;
use think\Log;
use app\service\deviceService;
use app\service\wotuService;
class Device extends Common{
	public function devicelist()
	{
		
		//根据当前账号查询小区
        $com = $this->pidTokenId();
        $whe['community_id'] = array('in',$com['community_id']);
        $devicelist = (new deviceService())->deviceList($whe);
       
       	foreach ($devicelist as $key => $value) {
       		$value["state"]="";
			$value["onlineState"]="";
       		$res=(new wotuService())->deviceinquiry($value["devicekey"]);
			$rest=json_decode($res, true);
            //echo "<pre>";var_dump($rest);die;
			if($rest["code"]=="WO_SUS1000"){
				$value["state"]=$rest["data"]["state"];
				$value["onlineState"]=$rest["data"]["onlineState"];
			}else{
			   // echo "<pre>";var_dump($rest);die;
            }
			$list[] = $value;
       	}
       
        $number=(new deviceService())->devicecount($whe);
        $this->assign('number',$number);
        if(!isset($list)){
            $this->assign('devicelist',$devicelist);
        }else{
            $this->assign('devicelist',$list);
        }
        $this->assign('list',$devicelist);
        return $this->fetch('device_list');
	}

	public function deviceadd(){
		if(request()->isPost()){
			$data=request()->post();
			//判断设备序列号是否重复        
            $deviceinfo = (new deviceService())->deviceinfo($data['devicekey']);
            if(!empty($deviceinfo)){
                $this->error('该设备已经已存在');
            }
            if($data["devicetype"]=="2"||$data["devicetype"]=="3"){
                if((empty($data["group"]))||(empty($data["building"]))||(empty($data["unit"]))){
                    $this->error("单元门组团楼栋单元不能为空");
                }
            }
            $communityinfo=Db::table("community")->where("id",$data["community_id"])->find();
            $data["community_name"]=$communityinfo["name"];
            //插入数据到数据库
            $result = (new deviceService())->deviceAdd($data);
            if($result){
                $this->success('门禁添加成功',url('deviceAdd'));
            }else{
                $this->error('门禁添加锁失败',url('deviceAdd'));
            }
		}else{
			$com = $this->pidTokenId();
            $whe['id'] = array('in',$com['community_id']);
	        $community = (new deviceService())->communityList($whe);
	        $this->assign('community',$community);
			return $this->fetch("device_add");
		}
	}

    public function deviceedit(){
        //查询小区信息
        $com = $this->pidTokenId();
        $whe['id'] = array('in',$com['community_id']);
        $community = (new deviceService())->communityList($whe);
        $this->assign('community',$community);

        if(request()->isGet()){
            $id = request()->param('id');
            if(!isset($id) && empty($id)){
                $this->error('设备不存在');
            }

            $info = Db::name('device')->where('id',$id)->find();
            $this->assign('info',$info);

            return $this->fetch('device_edit');
        }else{
            $data = request()->post();
            $result = Db::table("device")->where("id",$data["id"])->update(["devicekey"=>$data["devicekey"],'devicename'=>$data["devicename"],'localurl'=>$data['localurl'],'wiegandStatus'=>$data['wiegandStatus']]);
            if($result){
                $this->success('修改成功',url('deviceList'));
            }else{
                $this->error('修改失败');
            }
        }
    }


    public function useraccredit(){
        $userids = request()->param("userids");
        $deviceid = request()->param("deviceid");
        Db::startTrans();
        try{
            $useridarr = explode("," ,$userids);
            foreach ($useridarr as $id){
                $res = Db::table("wxuser_device")
                            ->where("wxuser_id",$id)
                            ->where("deviceid",$deviceid)
                            ->find();
                if(empty($res)){
                    Db::table('wxuser_device')->insert([
                        "wxuser_id" =>$id,
                        "deviceid" =>$deviceid,
                        "create_time" =>time(),
                        "update_time" =>time()
                    ]);
                }else{
                    Db::table('wxuser_device')
                        ->where("id",$res["id"])->update([
                        "update_time" =>time()
                    ]);
                }
            }
            // 提交事务
            Db::commit();
            return "授权成功";
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
        var_dump($wxuser_id,$deviceids);
    }
    public function usercancelaccredit(){
        $userids = request()->param("userids");
        $deviceid = request()->param("deviceid");
        Db::startTrans();
        try{
            $useridarr = explode("," ,$userids);
            foreach ($useridarr as $id){
                $res = Db::table("wxuser_device")
                    ->where("wxuser_id",$id)
                    ->where("deviceid",$deviceid)
                    ->find();
                if(!empty($res)){
                    Db::table('wxuser_device')
                        ->where("id",$res["id"])->delete();
                }
            }
            // 提交事务
            Db::commit();
            return "取消成功";
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $e->getMessage();
        }
        var_dump($wxuser_id,$deviceids);
    }

    public function userauth(){
        $deviceid = request()->get("deviceid");

        $deviceinfo = Db::table("device")->where("id",$deviceid)->find();
        // dump($data);exit();
        if(empty($deviceinfo)){
            return "设备信息错误";
        }
        $where["community_id"]=$deviceinfo["community_id"];
        if(($deviceinfo["devicetype"]=="2")||($deviceinfo["devicetype"]==3)){
            $where["group"] = $deviceinfo["group"];
            $where["building"] = $deviceinfo["building"];
            $where["unit"] = $deviceinfo["unit"];
        }
        $data = request()->get();
        //var_dump($data);
        if (!empty($data)){
            if(!empty($data['name1'])){
                $where['name'] = $data['name1'];//电话
            }

        }
        $this->assign('where',$where);
        //var_dump($where);
        $where = array_filter($where);
        //var_dump($where);//die;

        $page = request()->has('page') ? request()->get('page') : 1;
        $query= $where;
        $query["deviceid"]= $deviceid;
        //查询房屋信息
        $userlist = Db::name('wxuser')->where($where)->order('id asc')->paginate(100, false, [
            'page'  =>  $page,
            'query' =>  $query
        ]);
        $list=array();
        foreach ($userlist as $key => &$val) {
            $val["authstatus"] = 0;
            $res = Db::table("wxuser_device")
                ->where(["wxuser_id"=>$val["id"],"deviceid"=>$deviceid])
                ->find();
            if(!empty($res)){
                $val["authstatus"] = 1;
            }
            $list[] = $val;
        }

        $this->assign('list',$list);
        //echo "<pre>";var_dump($list);exit;
        $this->assign('userlist',$userlist);
        $this->assign('deviceid',$deviceid);
        foreach ($data as $k => $v) {
            $this->assign($k, $v);
        }

        return $this->fetch('user_auth');
    }

}